package com.pms.rpc;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.pms.authority.PermissionInfo;
import com.pms.controller.BaseController;
import com.pms.core.CommonConstant;
import com.pms.entity.*;
import com.pms.exception.R;
import com.pms.exception.RRException;
import com.pms.service.IBaseElementService;
import com.pms.service.IBaseMenuService;
import com.pms.service.IBaseUserService;
import com.pms.service.ICompanyCodeService;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCrypt;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * @author zyl
 * @create 2017-07-06 16:34
 **/
@Controller
@RequestMapping("api")
public class UserService  extends BaseController {
    Logger logger = LoggerFactory.getLogger(getClass());
    @Autowired
    IBaseUserService baseUserService;
    @Autowired
    IBaseElementService baseElementService;
    @Autowired
    IBaseMenuService baseMenuService;
    @Autowired
    ICompanyCodeService companyCodeService;


    @RequestMapping(value = "/user/username/{username}/{companyCode}", method = RequestMethod.GET, produces = "application/json")
    public @ResponseBody
    UserInfo getUserByUsername(@PathVariable("username") String username,@PathVariable("companyCode")String companyCode) {
        logger.info("getUserByUsername--->>> " + username);
        UserInfo info = new UserInfo();
        BaseUser user = baseUserService.getUserByUsername(username,companyCode);
        if(user!=null){
            BeanUtils.copyProperties(user, info);
            info.setId(user.getId().toString());
        }
        return info;
    }


    @RequestMapping(value = "/user/seleteById/{id}", method = RequestMethod.GET, produces = "application/json")
    public @ResponseBody
    BaseUser getUserByUserId(@PathVariable("id") Long id) {
        BaseUser baseUser = baseUserService.selectById(id);
        return baseUser;
    }

    @RequestMapping(value = "/user/selectByUser/{username}", method = RequestMethod.GET, produces = "application/json")
    public @ResponseBody
    Map<String, Object> selectByUser(@PathVariable("username") String username) {
        return baseUserService.selectMap(new EntityWrapper<BaseUser>().eq("username", username));
    }


    @RequestMapping(value = "/permissions", method = RequestMethod.GET)
    public @ResponseBody
    List<PermissionInfo> getAllPermission() {
        List<BaseMenu> menus = baseMenuService.selectList(null);
        List<PermissionInfo> result = new ArrayList<PermissionInfo>();
        PermissionInfo info = null;
        menu2permission(menus, result);
        List<BaseElement> elements = baseElementService.selectList(null);
        element2permission(result, elements);
        return result;
    }

    private void element2permission(List<PermissionInfo> result, List<BaseElement> elements) {
        PermissionInfo info;
        for (BaseElement element : elements) {
            info = new PermissionInfo();
            info.setCode(element.getCode());
            info.setType(element.getType());
            info.setUri(element.getUri());
            info.setMethod(element.getMethod());
            info.setName(element.getName());
            info.setMenu(element.getMenuId());
            result.add(info);
        }
    }

    private void menu2permission(List<BaseMenu> menus, List<PermissionInfo> result) {
        PermissionInfo info;
        for (BaseMenu menu : menus) {
            if (StringUtils.isBlank(menu.getHref())) {
                menu.setHref("/" + menu.getCode());
            }
            info = new PermissionInfo();
            info.setCode(menu.getCode());
            info.setType(CommonConstant.RESOURCE_TYPE_MENU);
            info.setName(CommonConstant.RESOURCE_ACTION_VISIT);
            String uri = menu.getHref();
            if (!uri.startsWith("/")) uri = "/" + uri;
            info.setUri(uri);
            info.setMethod(CommonConstant.RESOURCE_REQUEST_METHOD_GET);
            result.add(info);
            info.setMenu(menu.getTitle());
        }
    }

    @RequestMapping(value = "/user/un/{username}/permissions/{menuType}/{companyCode}", method = RequestMethod.GET)
    public @ResponseBody
    List<PermissionInfo> getPermissionByUsername(@PathVariable("username") String username,@PathVariable("menuType")Integer menuType,@PathVariable("companyCode")String companyCode) {
        List<PermissionInfo> result = new ArrayList<PermissionInfo>();
        BaseUser user = baseUserService.getUserByUsername(username,companyCode);
        if(menuType==1){//查询管网
            List<BaseMenu> menuList= baseMenuService.selectTreeTrue(user.getId());
            if (menuList.size()==0){
                return result;
            }
        }
        List<BaseMenu> menus = baseMenuService.selectAuthorityMenu(user.getId(),menuType,user.getRoleType());
        PermissionInfo info = null;
        for (BaseMenu menu : menus) {
            if (null==menu||null==menu.getId()){
                continue;
            }
            info = new PermissionInfo();
            info.setCode(menu.getCode());
            info.setIcon(menu.getIcon());
            info.setMenuType(menu.getMenuType());
            info.setId(menu.getId().toString());
            info.setParentId(menu.getParentId().toString());
            info.setType(CommonConstant.RESOURCE_TYPE_MENU);
            info.setName(CommonConstant.RESOURCE_ACTION_VISIT);
            if (!StringUtils.isBlank(menu.getHref())) {
                String uri = menu.getHref();
                if (!uri.startsWith("/")) uri = "/" + uri;
                info.setUri(uri);
            }
            info.setMethod(CommonConstant.RESOURCE_REQUEST_METHOD_GET);
            info.setMenu(menu.getTitle());
            result.add(info);
        }
        List<BaseElement> elements = baseElementService.getAuthorityElement(user.getGroupType(),user.getRoleType(),user.getId().toString());
        for (BaseElement element : elements) {
            info = new PermissionInfo();
            info.setCode(element.getCode());
            info.setMenuType(element.getMenuType());
            info.setType(element.getType());
            info.setUri(element.getUri());
            info.setMethod(element.getMethod());
            info.setName(element.getName());
            info.setMenu(element.getMenuId());
            result.add(info);
        }
        return result;
    }

//    @RequestMapping(value = "/user/un/{username}/system/{companyCode}", method = RequestMethod.GET)
//    @ResponseBody
//    public String getSystemsByUsername(@PathVariable("username") String username,@PathVariable("companyCode") String companyCode) {
//        Long userId = baseUserService.getUserByUsername(username,companyCode).getId();
//        return JSONObject.toJSONString(baseMenuService.getUserAuthoritySystemByUserId(userId.intValue()));
//    }
//
//    @RequestMapping(value = "/user/un/{username}/menu/parent/{parentId}/{companyCode}", method = RequestMethod.GET)
//    @ResponseBody
//    public String getMenusByParentId(@PathVariable("username") String username, @PathVariable("parentId") Integer parentId,@PathVariable("companyCode") String companyCode) {
//        Long userId = baseUserService.getUserByUsername(username,companyCode).getId();
//        try {
//            if (parentId == null || parentId < 0) {
//                parentId = baseMenuService.getUserAuthoritySystemByUserId(userId.intValue()).get(0).getId();
//            }
//        } catch (Exception e) {
//            return JSONObject.toJSONString(new ArrayList<MenuTree>());
//        }
//        return JSONObject.toJSONString(getMenuTree(baseMenuService.getUserAuthorityMenuByUserId(userId.intValue()), parentId));
//    }
//
//    private List<MenuTree> getMenuTree(List<BaseMenu> menus, int root) {
//        List<MenuTree> trees = new ArrayList<MenuTree>();
//        MenuTree node = null;
//        for (BaseMenu menu : menus) {
//            node = new MenuTree();
//            BeanUtils.copyProperties(menu, node);
//            trees.add(node);
//        }
//        return TreeUtil.bulid(trees, root);
//    }

    @RequestMapping(value = "/user/seleteByuser/{username}", method = RequestMethod.GET, produces = "application/json")
    public @ResponseBody
    BaseUser seleteByuser(@PathVariable("username") String username) {
        BaseUser baseUser = baseUserService.selectOne(new EntityWrapper<BaseUser>().eq("username", username));
        return baseUser;
    }

    @RequestMapping(value = "/user/getByuseraccount/{username}/{companyCode}", method = RequestMethod.POST, produces = "application/json")
    public @ResponseBody
    BaseUser getByuseraccount(@PathVariable("username") String username, @PathVariable("companyCode") String companyCode) {
        BaseUser baseUser = baseUserService.getByuseraccount(username, companyCode);
        return baseUser;
    }
    /**
     * 查询所有
     *
     * @return
     */
    @RequestMapping(value = "/getAll", method = RequestMethod.GET)
    @ResponseBody
    public List<Map<String, Object>> getAll() {
        return companyCodeService.selectMaps(null);
    }


    @RequestMapping(value = "/user/getSingleuserInfo/{id}", method = RequestMethod.GET, produces = "application/json")
    public @ResponseBody
    UserInfo getSingleuserInfo(@PathVariable("id") Long id) {
        UserInfo info = new UserInfo();
        BaseUser user = baseUserService.selectById(id);
        BeanUtils.copyProperties(user, info);
        info.setId(user.getId().toString());
        return info;
    }

    @RequestMapping(value = "/user/getListByPhone/{phone}",method = RequestMethod.POST, produces="application/json")
    public @ResponseBody
    int getListByPhone(@PathVariable("phone")String phone){
        return baseUserService.selectCount(new EntityWrapper<BaseUser>().eq("mobile_phone",phone));
    }


    @RequestMapping(value = "/user/selectByCompanyCode/{phone}",method = RequestMethod.POST, produces="application/json")
    public @ResponseBody
    List<Map<String,Object>> selectByCompanyCode(@PathVariable("phone")String phone){
        return  baseUserService.selectByCompanyCode(phone);
    }


    @RequestMapping(value = "/user/updataPhoneCompanyCodePassWord/{phone}/{companyCode}/{passWord}", method = RequestMethod.POST, produces = "application/json")
    public
    @ResponseBody boolean updataPhoneCompanyCodePassWord(@PathVariable("phone")String  phone,@PathVariable("companyCode")String  companyCode,@PathVariable("passWord")String passWord){
        BaseUser baseUser = baseUserService.selectOne(new EntityWrapper<BaseUser>().eq("mobile_phone",phone).and().eq("company_code",companyCode));
       if (null==baseUser){return  false;}
        baseUser.setPassword(BCrypt.hashpw(passWord,baseUser.getPassword()));
        baseUser.setUpdTime(new Date());
        baseUser.setUpdName(baseUser.getName());
        baseUserService.updateById(baseUser);
        return  true;
    }

    @RequestMapping(value = "/user/selectbyPipUser/{id}",method = RequestMethod.GET, produces="application/json")
    public @ResponseBody
    UserInfo selectbyPipUser(@PathVariable("id")Long id){
        UserInfo info = new UserInfo();
        BaseUser user = baseUserService.selectbyPipUser(id);
        BeanUtils.copyProperties(user, info);
        info.setId(user.getId().toString());
        return info;
    }


    /**
     * 提供API接口给终端
     * @param username
     * @param companyCode
     * @return
     */
    @RequestMapping(value = "/user/un/{username}/permissions/{companyCode}/api", method = RequestMethod.GET)
    public @ResponseBody
    List<PermissionInfo> getApiPermissionByUsername(@PathVariable("username") String username,@PathVariable("companyCode")String companyCode) {
        List<PermissionInfo> result = new ArrayList<PermissionInfo>();
        BaseUser user = baseUserService.getUserByUsername(username,companyCode);
        if (user==null){return  result;}
        List<BaseMenu> menus = baseMenuService.ApiSelectAuthorityMenu(user.getId(),user.getRoleType());
        if (menus==null){return  result;}
        PermissionInfo info = null;
        for (BaseMenu menu : menus) {
            if (null==menu||null==menu.getId()){
            continue;
            }
            info = new PermissionInfo();
            info.setId(menu.getId().toString());
            info.setType(CommonConstant.RESOURCE_TYPE_MENU);
            info.setMenuType(menu.getMenuType());
            info.setMenu(menu.getTitle());
            result.add(info);
        }
        List<BaseElement> elements = baseElementService.getAuthorityElement(user.getGroupType(),user.getRoleType(),user.getId().toString());
        for (BaseElement element : elements) {
            info = new PermissionInfo();
            info.setCode(element.getCode());
            info.setType(element.getType());
            info.setMenuType(element.getMenuType());
            info.setUri(element.getUri());
            info.setMethod(element.getMethod());
            info.setName(element.getName());
            info.setMenu(element.getMenuId());
            result.add(info);
        }
        return result;
    }


    /**
     * 查询API查询是否有权限
     * @param userId
     * @param menuType
     * @param title
     * @return
     */
    @RequestMapping(value = "/user/un/getApiPermission/{userId}/{menuType}/api", method = RequestMethod.GET)
    public @ResponseBody
    Map<String, Object> getApiPermission(@PathVariable("userId") Long userId,@PathVariable("menuType")Integer menuType,String title,Integer permissionsType,String method) {
        Map<String, Object> menus =new HashMap<>();
      if (permissionsType ==1){//查询菜单
           menus = baseMenuService.getApiPermissionMenu(userId, menuType, title);
      }else if (permissionsType ==2){//查询权限
          BaseUser baseUser = baseUserService.selectById(userId);
          if (null!=baseUser){
              menus = baseElementService.getApiPermissionElement(userId,baseUser.getGroupType(),baseUser.getRoleType(),method,title,menuType);
          }
         }
        return menus;
    }

    /**
     * 提供给超级管理员所用
     * @param username
     * @return
     */
    @RequestMapping(value = "/user/getBySuperUser/{username}",method = RequestMethod.POST, produces="application/json")
    public @ResponseBody
    BaseUser getBySuperUser(@PathVariable("username") String username) {
        BaseUser baseUser = baseUserService.getBySuperUser(username);
        return baseUser;
    }
    /**
     * 提供给超级管理员所用
     * @param username
     * @return
     */
    @RequestMapping(value = "/user/getSuperUserByUsername/{username}", method = RequestMethod.GET,produces = "application/json")
    public @ResponseBody
    UserInfo getUserByUsername(@PathVariable("username") String username) {
        logger.info("getUserByUsername--->>> " + username);
        UserInfo info = new UserInfo();
        BaseUser user = baseUserService.getBySuperUser(username);
        if(user!=null){
            BeanUtils.copyProperties(user, info);
            info.setId(user.getId().toString());
        }
        return info;
    }


    /**
     * 提供给超级管理员所用
     * @param username
     * @return
     */
    @RequestMapping(value = "/user/un/{username}/getPermissionBysuperAdmin", method = RequestMethod.GET)
    public @ResponseBody
    List<PermissionInfo> getApiPermissionByUsername(@PathVariable("username") String username) {
        List<PermissionInfo> result = new ArrayList<PermissionInfo>();
        BaseUser user = baseUserService.getBySuperUser(username);
        if (user==null){return  result;}
        List<BaseMenu> menus = baseMenuService.getAuthorityMenuAndSuperadmin(user.getId());
        if (menus==null){return  result;}
        PermissionInfo info = null;
        for (BaseMenu menu : menus) {
            if (null==menu||null==menu.getId()){
                continue;
            }
            info = new PermissionInfo();
            info.setCode(menu.getCode());
            info.setIcon(menu.getIcon());
            info.setMenuType(menu.getMenuType());
            info.setId(menu.getId().toString());
            info.setParentId(menu.getParentId().toString());
            info.setType(CommonConstant.RESOURCE_TYPE_MENU);
            info.setName(CommonConstant.RESOURCE_ACTION_VISIT);
            if (!StringUtils.isBlank(menu.getHref())) {
                String uri = menu.getHref();
                if (!uri.startsWith("/")) uri = "/" + uri;
                info.setUri(uri);
            }
            info.setMethod(CommonConstant.RESOURCE_REQUEST_METHOD_GET);
            info.setMenu(menu.getTitle());
            result.add(info);
        }
        List<BaseElement> elements = baseElementService.getAndSuperAdminAuthorityElement(user.getId().toString());
        for (BaseElement element : elements) {
            info = new PermissionInfo();
            info.setCode(element.getCode());
            info.setType(element.getType());
            info.setMenuType(element.getMenuType());
            info.setUri(element.getUri());
            info.setMethod(element.getMethod());
            info.setName(element.getName());
            info.setMenu(element.getMenuId());
            result.add(info);
        }
        return result;
    }

    @RequestMapping(value = "/user/getByCompany/{companyCode}",method = RequestMethod.POST, produces="application/json")
    public @ResponseBody
    Map<String,Object> getByCompany(@PathVariable("companyCode")String companyCode){
        return   companyCodeService.selectMap(new EntityWrapper<CompanyCode>().eq("company_code",companyCode));
    }
}
